import {
	SerializedError,
	createAsyncThunk,
	createSlice,
} from '@reduxjs/toolkit'
import { RootState, TUser } from '../../types'
import api from '../../../api'
import { TEditUserRequest } from '../../../api/api'

type TUserState = {
	data: TUser | null
	token: string
	loading: boolean
	error: SerializedError | null | unknown
}

const initialState: TUserState = {
	data: null,
	token: '',
	loading: false,
	error: null,
}

const sliceName = 'user'

export const fetchEditUser = createAsyncThunk<TUser, TEditUserRequest>(
	`${sliceName}/fetchEditedUser`,
	async (params, { getState }) => {
		try {
			const response = await api((getState() as RootState).user.token).editUser(
				params
			)
			return response
		} catch (error) {
			return error
		}
	}
)

export const userSlice = createSlice({
	name: sliceName,
	initialState,
	reducers: {
		setUser: (state, action) => {
			state.data = action.payload
			state.loading = false
		},
		setToken: (state, action) => {
			state.token = action.payload
			state.loading = false
		},
	},
	extraReducers: (builder) => {
		builder
			.addCase(fetchEditUser.fulfilled, (state, action) => {
				state.data = action.payload
				state.loading = false
			})
			.addCase(fetchEditUser.pending, (state) => {
				state.loading = true
				state.error = null
			})
			.addCase(fetchEditUser.rejected, (state, action) => {
				state.error = action.payload
				state.loading = false
			})
	},
})
